package com.honeybee.cloud.framework.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 资源过滤器
 * 所有的资源请求在路由之前进行前置过滤
 * 如果请求头不包含 Authorization参数值，直接拦截不再路由
 *
 * @Description
 * @Author DELL
 * @Create 2018-12-27
 * @Since 1.0.0
 */
@Slf4j
@Component
public class OauthFilter extends ZuulFilter {


    private String bearerStartStr="Bearer";
    private String basicStartStr="Basic";

    private String authorization="Authorization";
    /**
     * 过滤器的类型 pre表示请求在路由之前被过滤
     *
     * @return 类型
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器的执行顺序
     *
     * @return 顺序 数字越大表示优先级越低，越后执行
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 过滤器是否会被执行
     *
     * @return true
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤逻辑
     *
     * @return 过滤结果
     */
    @Override
    public Object run() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();
        log.debug("send {} request to {}", request.getMethod(), request.getRequestURL().toString());
        String accessToken = request.getHeader(authorization);
        log.warn("accessToken:{}", accessToken);
        if (StringUtils.isEmpty(accessToken)) {
            log.warn("Authorization token is empty");
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            requestContext.setResponseBody("Authorization token is empty");
            return null;
        }
        boolean conformityToken=!accessToken.startsWith(bearerStartStr)&&!accessToken.startsWith(basicStartStr);
        if (conformityToken) {
            log.warn("Authorization token non conformity");
            requestContext.setSendZuulResponse(false);
            requestContext.setResponseStatusCode(401);
            requestContext.setResponseBody("Authorization token non conformity");
            return null;
        }
        log.debug("Authorization token is ok");
        return null;
    }
}

